import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import {ElMessage} from 'element-plus'
import {staticRoutes} from '@/router/routes'
import { getUserInfoApi, loginApi, logoutApi } from '@/api/acl/login';


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

	actions: {
   async login (username: string, password: string) {
      // 发送登录请求
      const result = await loginApi(username,password)

      // 请求成功之后，取出token保存起来 pinia 和 local中
      const token = result.token
      this.token = token 
      setToken(token)
    },

    async getInfo () {
      // 请求获取用户信息
      const result = await getUserInfoApi()
      // 请求成功之后，读取用户信息name和avatar，保存到state
      const { name,avatar } = result
      this.name = name
      this.avatar = avatar
      // 将静态路由保存到state
      this.menuRoutes = staticRoutes
    },

   async reset () {
    // 如果当前存在用户名，请求退出登录的接口
    if(this.name){
      await logoutApi()  // 加上await之后，下面的代码是在请求成功之后执行的
    }

      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
    },
	},
});
